<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\mall\home;

use app\admin\model\Attachment;
use app\index\controller\Home;
use app\mall\model\Merch as MerchModel;
use app\mall\model\Category as CategoryModel;
use app\mall\model\Goods as GoodsModel;
use app\user\model\Level;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use think\facade\Db;
/**
 * 商品分类
 * @package app\mall\home
 */
class Goods extends Home
{
    /**
     * 跳转到第一个有权限访问的url
     * @author PaulXun <paulxun@qq.com>
     * @return mixed|string
     * sty: 'color: #188b86;background: #cbeae9;'
    sty: 'color: #67318b;background: #dbcee5;'
    sty: 'color: #97ab6f;background: #eaf3d6;'
    sty: 'color: #a53a00;background: #fadfc9;'
     */
    public function index($id = 0)
    {
		$category = CategoryModel::where('pid', '=', 0)->where('status', '=', 1)->order('sort')->select();
        $category = json_decode(json_encode($category),true) ;
        $category[0]['color'] = 'color:#188b86;background:#cbeae9;';
        $category[1]['color'] = 'color:#67318b;background:#dbcee5;';
        $category[2]['color'] = 'color:#97ab6f;background:#eaf3d6;';
        $category[3]['color'] = 'color:#a53a00;background:#fadfc9;';
//var_dump($category);exit;
		$this->assign('category', $category);

		$child = [];
		if ($id > 0) {
			$info = CategoryModel::find($id);
			if ($info && $info['pid'] > 0) {
				$child_list= CategoryModel::where('pid', '=', $info['pid'])->where('status', '=', 1)->order('sort')->field('id,title')->select();
			} else {
				$child_list= CategoryModel::where('pid', '=', $id)->where('status', '=', 1)->order('sort')->field('id,title')->select();
			}
			if ($child_list) $child = $child_list->toArray();
		}
		$this->assign('child', $child);
		$uid = is_login();
		$vip = VipModel::where('member_id', '=', $uid)->find();
		//level：0 零售  1	批发  2	县代   3	 市代   4  省代
        //agent：0全部 1泡浴 2食疗
        //price：price price_pifa price_xian price_shi price_sheng
		if (request()->isAjax()){
			$data = request()->param();
			// 构建查询参数
			$map = [
				['status', '=', 1],
			];
			
			// 获取查询模式
			if (!empty($data['model']) && $data['model'] == 'index') {
				$map[] = ['index', '=', 1];
			}
			//获取查询关键字
			$keyword = request()->param('keyword');
			
			if ($keyword != ''){
				$map[] = ['title', 'like', "%$keyword%"];
			} else {
				if ($id > 0) {
					$ids = CategoryModel::getChildsId($id);
					$ids[] = $id;
					$map[] = ['cid', 'in', $ids];
				}
			}
			$order = 'sort asc';
			
			$data_list = GoodsModel::where($map)->order($order)->field('id,title,agent,logo,price,price_pifa,price_xian,price_shi,price_sheng,cid')->paginate(8);
			$ajax = $data_list->items();
			foreach ($ajax as $key => $value) {
				$ajax[$key]['cover'] = get_file_path($value['logo']);
				if($vip['agent'] == 0){ //代理全部产品
                    $ajax[$key]['price'] = Level::price_list($vip,$value);
                }elseif($vip['agent'] == 1){ //代理泡浴类产品
                    if($value['agent'] == 1){
                        $ajax[$key]['price'] = Level::price_list($vip,$value);
                    }else{
                        $ajax[$key]['price'] = $value['price']/100;
                    }
				}elseif($vip['agent'] == 2){
                    if($value['agent'] == 2){
                        $ajax[$key]['price'] = Level::price_list($vip,$value);
                    }else{
                        $ajax[$key]['price'] = $value['price']/100;
                    }
                }

//				$category = CategoryModel::where('status', '=', 1)->where('id', '=', $value['cid'])->where('auth', 'find in set', $vip['shop'])->find();
//				if (!$vip || $vip['status'] == 0  || !$category) $ajax[$key]['price'] = '???';
			}

			$data['items'] = $ajax;
			$data['last_page'] = $data_list->lastPage();
			$data['total'] = $data_list->total();	
			$data['current_page'] = $data_list->currentPage();
			$data['list_rows'] = $data_list->listRows();
            $data['paoji'] = $this->category_list(1);
            $data['fenji'] = $this->category_list(2);
            $data['shuiji'] = $this->category_list(3);
            $data['taohe'] = $this->category_list(4);
			if ($ajax) {
				$this->success('加载成功', '', $data);
			} else {
				$this->error('未找到相关商品');
			}
		}
		//重新定义active
		$this->view->active = 'goods';
		// 渲染模板
		return $this->fetch();
    }
    /**
     * 获取分类
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function category_list($id){
        $uid = is_login();
        $vip = VipModel::where('member_id', '=', $uid)->find();
        $ids = CategoryModel::getChildsId($id);
        $ids[] = $id;
        $map[] = ['cid', 'in', $ids];
        $order = 'sort asc';

        $data_list = GoodsModel::where($map)->order($order)->field('id,title,agent,logo,price,price_pifa,price_xian,price_shi,price_sheng,er_price_xian,er_price_qu,er_price_shi,er_price_sheng,san_price_xian,san_price_qu,san_price_shi,san_price_sheng,cid')->paginate(8);
        $ajax = $data_list->items();
        foreach ($ajax as $key => $value) {
            $ajax[$key]['cover'] = get_file_path($value['logo']);
            if($vip['agent'] == 0){ //代理全部产品
                $ajax[$key]['price'] = Level::price_list($vip,$value);

            }elseif($vip['agent'] == 1){ //代理泡浴类产品
                if($value['agent'] == 1){
                    $ajax[$key]['price'] = Level::price_list($vip,$value);
                }else{
                    $ajax[$key]['price'] = $value['price']/100;
                }
            }elseif($vip['agent'] == 2){
                if($value['agent'] == 2){
                    $ajax[$key]['price'] = Level::price_list($vip,$value);
                }else{
                    $ajax[$key]['price'] = $value['price']/100;
                }
            }

        }

        $data['items'] = $ajax;
        $data['last_page'] = $data_list->lastPage();
        $data['total'] = $data_list->total();
        $data['current_page'] = $data_list->currentPage();
        $data['list_rows'] = $data_list->listRows();
        return $data;
    }



	/**
	 * 商品详情
	 * @author PaulXun <paulxun@qq.com>
	 * @return mixed
	 */
	public function detail($id = 0)
	{
		if ($id == 0) $this->error('商品参数错误');
		$goods = GoodsModel::getOne($id);

		if (!$goods) $this->error('该商品不存在或已下架');

		if(empty($goods['content'])){
            $goods['content'] = 0;
        }
		// 获取会员信息
		$uid = is_login();
		$vip = VipModel::where('member_id', '=', $uid)->find();
        if($vip['agent'] == 0){ //代理全部产品
            $goods['price'] = Level::price_list($vip,$goods);
        }elseif($vip['agent'] == 1){ //代理泡浴类产品
            if($goods['agent'] == 1){
                $goods['price'] = Level::price_list($vip,$goods);
            }else{
                $goods['price'] = $goods['price']/100;
            }
        }elseif($vip['agent'] == 2){
            if($goods['agent'] == 2){
                $goods['price'] = Level::price_list($vip,$goods);
            }else{
                $goods['price'] = $goods['price']/100;
            }
        }
		$goods['images'] = [];
		
		$category = CategoryModel::where('status', '=', 1)->where('id', '=', $goods['cid'])->where('auth', 'find in set', $vip['shop'])->find();
        $goods['videos'] = [];
        $video = Attachment::where('id','=',$goods['goods_video'])->find();
        $goods['videos'] = $video['path'];
//        var_dump($goods['videos']);exit;
		if (!$vip || $vip['status'] == 0 || !$category) $goods['price'] = '???';
		
		if ($goods['pics']) {
			// 批量获取banner
			$pics = explode(',', $goods['pics']);
			foreach ($pics as $pic) {
				$goods['images'][] = [
					'id' => $pic,
					'image' => get_file_path($pic),
				];
			}
		} else {
			$goods['images'][] = [
				'id' => $goods['logo'],
				'image' => get_file_path($goods['logo']),
			];
		}
		$this->assign('detail', $goods);
		//重新定义active
		$this->view->active = 'goods';
		// 渲染模板
		return $this->fetch();
	}
	//生成二维码
	public function qrcode($code = '')
	{
		$url = real_url('merch/index/wxsign');
		$url = $url.'?code='.$code;
		cache('wx'.$code, config('wechat.appid'), 300);
		$qrcode = new QrcodeTool;
		return $qrcode->make($url, 4);
	}
	
	//获取登录状态
	public function code($code = 0)
	{	
		if ($code === 0) $this->error("参数错误");
		
		if ($this->request->isAjax()) {
			$openid = cache('wx'.$code);
			if (!$openid) {
				$this->error('扫码超时');
			}
			if ($openid == config('wechat.appid')) return json(['code' => -1, 'msg' => 'Waiting']);
			$child = cache('child'.$code);
			if (!$child) return json(['code' => -2, 'msg' => '等待用户操作']);
			
			$MemberModel = new MemberModel();
			$user = $MemberModel::where('openid|unionid', '=', $openid)->where('status', 1)->find();
			if(!$user){
				$this->error('用户不存在');
			}
			// 查找用户选择的子商户
			$merch_child = ChildModel::getInfo($child);
			if (!$merch_child || in_array($user['id'], explode(',', $merch_child['uids'])) == false) {
				$this->error('暂无可登录商户，请联系管理员');
			}
			if ($MemberModel->autoLogin($user['id'])) {
				session('child', $child);
				$this->success('登录成功');
			} else {
				$this->error($MemberModel->getError());
			}
		}
	}
	//微信登录
	public function wxsign($code = '')
	{
		// $redis = new \Redis();
		// $redis->connect('127.0.0.1', 6379);
		// $arList = $redis->keys("*");
		// dd($arList);
		if ($code !== '') cookie('code', $code);
		$code = cookie('code');
		if (!$code) {
			$tips = [
				'code'		=> 0,
				'title'		=> '授权码获取失败',
				'summary'	=> '微信授权登录失败，请重新扫码！',
			];
			$this->assign('tips', $tips);
		} else {
			// 判断登录
			$uid = is_login();
			if (!$uid) {
				cookie('__backurl__', $_SERVER['REQUEST_URI']);
				$this->redirect(url('user/member/wxlogin'));
			}
			$user = MemberModel::where('id', $uid)->where('status', 1)->find();
			if (!$user) {
				$tips = [
					'code'		=> 0,
					'title'		=> '登录失败',
					'summary'	=> '微信授权登录失败，如有需要请联系管理员，点击确定关闭该页面！',
				];
				$this->assign('tips', $tips);
			} else {
				cache('wx'.$code, $user['openid'], 300);
			}
			$child_list = ChildModel::where('uids', 'find in set', $user['id'])->where('status', '=', 1)->select()->toarray();
			if (!$child_list) {
				$tips = [
					'code'		=> 0,
					'title'		=> '查找商户失败',
					'summary'	=> '微信授权登录失败，如有需要请联系管理员，点击确定关闭该页面！',
				];
				$this->assign('tips', $tips);
			} else {
				$this->assign('child', $child_list);
			}
		}
		
		if (request()->isPost()){
			$data = request()->post();
			if (!isset($data['id'])) $this->error('请选择终端');
			cache('child'.$code, $data['id'], 300);
			$this->success('授权成功');
		}
		//微信SDK支持
		$wxsdk = new Wxsdk;
		$jssdk = $wxsdk->getWxSdk();
		if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		
		// 渲染模板
		return $this->fetch();
	}
    /**
     * 退出登录
     * @author PaulXun <paulxun@qq.com>
     */
	public function logout()
	{
	    session(null);
	    cookie('member_id', null);
	    cookie('member_signin_token', null);
	    $this->redirect(url('merch/index/login'));
	}
}
